package com.mmp.main.util;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;

import com.mmp.common.bo.Message;
import com.mmp.common.util.Common;
import com.mmp.common.util.DateUtil;
import com.mmp.main.entity.Hospital;
import com.mmp.main.entity.HospitalDevice;
import com.mmp.main.entity.Site;
import com.mmp.main.entity.User;

public class WebUtil {

	public static String getCurrentSiteName(HttpServletRequest request) {
		User user = getSessionUser(request);
		Site site = user.getSite();
		if (user == null || site == null)
			return null;

		Hospital location = getSessionLocation(request);

		String siteName = null;
		if (!site.getContainsSeveralLocations()) {
			siteName = location.getName();
		} else {
			if (location == null)
				siteName = site.getName();
			else
				siteName = site.getName() + " - " + location.getName();
		}
		return siteName;
	}

	public static boolean currentLocationIsHealthCenter(HttpServletRequest request) {
		return getSessionLocation(request).getHealthCenter();
	}

	public static boolean currentUserIsDirectorateAdmin(HttpServletRequest request) {
		return request.isUserInRole(Enums.SYS_ROLES.DIRECTORATE_ADMIN.getRoleName());
	}

	public static boolean currentUserBelongsToMovingTeam(HttpServletRequest request) {
		return getSessionUser(request).getMovingTeam();
	}

	public static boolean userHasRightToChangeSessionHospital(HttpServletRequest request) {
		return currentUserIsDirectorateAdmin(request) || currentUserBelongsToMovingTeam(request);
	}

	public static boolean userHasRightToCloseJobOrder(HttpServletRequest request) {
		// return getSessionUserType(request) !=
		// Enums.USER_TYPE.SITE_MANAGER.getId();
		return request.isUserInRole(Enums.SYS_ROLES.DEPARTMENT_HEAD.getRoleName());
	}

	public static boolean userHasRightToAcceptSparePartsQuotation(HttpServletRequest request) {
		// return getSessionUserType(request) !=
		// Enums.USER_TYPE.SITE_MANAGER.getId();
		return request.isUserInRole(Enums.SYS_ROLES.DEPARTMENT_HEAD.getRoleName());
	}

	public static boolean userHasRightToWithdrawFromSPInventoryWithoutJobOrder(HttpServletRequest request) {
		// return getSessionUserType(request) !=
		// Enums.USER_TYPE.SITE_MANAGER.getId();
		return request.isUserInRole(Enums.SYS_ROLES.DEPARTMENT_HEAD.getRoleName());
	}

	public static boolean userHasRightToUpdateCompletedPhasesOfJobOrderFollowup(HttpServletRequest request) {
		// return getSessionUserType(request) !=
		// Enums.USER_TYPE.SITE_MANAGER.getId();
		return request.isUserInRole(Enums.SYS_ROLES.DEPARTMENT_HEAD.getRoleName());
	}

	public static boolean currentUserHasViewPrivilegesOnly(HttpServletRequest request) {
		return request.isUserInRole(Enums.SYS_ROLES.DIRECTORATE_ADMIN.getRoleName())
				|| request.isUserInRole(Enums.SYS_ROLES.HOSPITAL_DIRECTOR.getRoleName());
	}

	public static User getSessionUser(HttpServletRequest request) {
		HttpSession s = request.getSession(false);
		User sUser = null;
		if (s != null)
			sUser = (User) s.getAttribute("user");
		return sUser;
	}

	public static Hospital getSessionLocation(HttpServletRequest request) {
		HttpSession s = request.getSession(false);
		if (s != null)
			return (Hospital) s.getAttribute("sessionHospital");
		return null;
	}

	public static Integer getSessionUserType(HttpServletRequest request) {
		HttpSession s = request.getSession(false);
		User sUser = null;
		if (s != null) {
			sUser = (User) s.getAttribute("user");
			if (sUser != null)
				return sUser.getUserType();
		}
		return 0;
	}

	public static String getSessionMessage(HttpServletRequest request) {
		Message msg = null;
		HttpSession s = request.getSession(false);
		if (s != null) {
			msg = (Message) s.getAttribute("msg");
			s.removeAttribute("msg");
		}
		if (msg != null) {
			if (msg.getType() == Message.MESSAGE_TYPE.ERROR)
				return "<h3 class='error_msg'>" + msg.getText() + "</h3>";
			else if (msg.getType() == Message.MESSAGE_TYPE.WARNING)
				return "<h3 class='warning_msg'>" + msg.getText() + "</h3>";
			else if (msg.getType() == Message.MESSAGE_TYPE.SUCCESS)
				return "<h3 class='success_msg'>" + msg.getText() + "</h3>";
		}
		return "";
	}

	public static Integer getParamValueAsInteger(HttpServletRequest request, String paramName, Integer defaultValue) {
		try {
			return Integer.parseInt(request.getParameter(paramName));
		} catch (Exception e) {
			return defaultValue;
		}
	}

	public static Float getParamValueAsFloat(HttpServletRequest request, String paramName, Float defaultValue) {
		try {
			return Float.parseFloat(request.getParameter(paramName));
		} catch (Exception e) {
			return defaultValue;
		}
	}

	public static String getParamValue(HttpServletRequest request, String paramName, String defaultValue) {
		String inputStr = request.getParameter(paramName);
		if (inputStr != null && !inputStr.trim().isEmpty())
			// /return StringEscapeUtils.escapeSql(inputStr);
			return inputStr;
		// return StringEscapeUtils.escapeSql(defaultValue);
		return defaultValue;
	}

	public static Date getParamValueAsDate(HttpServletRequest request, String paramName, Date defaultValue) {
		try {
			Date d = DateUtil.convertToDate(request.getParameter(paramName));
			return (d != null) ? d : defaultValue;
		} catch (Exception e) {
			return defaultValue;
		}
	}

	public static String decodeQueryStringParameter(HttpServletRequest request, String paramName) {

		/*
		 * try { return URLDecoder.decode(request.getParameter(paramName),
		 * "UTF-8"); } catch (UnsupportedEncodingException e) { Common.log(e);
		 * return null; }
		 */

		try {
			String value = new String(request.getParameter(paramName).getBytes("iso-8859-1"), "utf-8");
			return (value != null) ? value : "";
		} catch (UnsupportedEncodingException e) {
			Common.log(e);
			return "";
		}

	}

	public static String getRequestUri(HttpServletRequest request, boolean getLast) {

		String originalRequestUri = null;
		if (!getLast)
			originalRequestUri = (String) request.getAttribute("javax.servlet.forward.request_uri");
		if (originalRequestUri == null)
			originalRequestUri = request.getServletPath();

		return originalRequestUri.substring(originalRequestUri.lastIndexOf("/") + 1);
	}

	public static String getRequestUri(HttpServletRequest request) {
		return getRequestUri(request, false);
	}

	public static String getSearchDisplayURL(HttpServletRequest request) {
		return getRequestUri(request) + "Search";
	}

	public static String getSearchProcessURL(HttpServletRequest request) {
		return getRequestUri(request).replace("Search", "");
	}

	public static String getDeviceStatusName(HospitalDevice device) {

		int status = device.getStatus();

		if (status == Enums.DEVICE_STATUS.WORK_PROPERLY.getStatus())
			return "يعمل";
		else if (status == Enums.DEVICE_STATUS.UNDER_MAINTENANCE.getStatus())
			return "تحت الصيانة";
		else if (status == Enums.DEVICE_STATUS.SCRAPPED.getStatus())
			return "مكهن";
		else if (status == Enums.DEVICE_STATUS.TRANSFERRED.getStatus())
			return "تم نقله أو سحبه";
		else
			return "غير معلوم";
	}

	public static Integer getSiteIdFromEndPointSession(Session session) {
		List<String> list = session.getRequestParameterMap().get("siteId");
		if (list == null || list.isEmpty())
			return null;

		String siteId = list.get(0);
		// Common.log("********************************** endpoint siteId = " +
		// siteId);
		try {
			return Integer.parseInt(siteId);
		} catch (Exception e) {
			return null;
		}
	}

	public static boolean jobOrderPhaseIsPartOfMiddlePhases(int phaseId) {
		return phaseId == Enums.JOBORDER_FOLLOWUP_PHASES.AGENT_REPORT_UPLOADED.getId()
				|| phaseId == Enums.JOBORDER_FOLLOWUP_PHASES.QUOTATION_RECIEVED.getId();
		// || phaseId ==
		// Enums.JOBORDER_FOLLOWUP_PHASES.QUOTATION_ACCEPTED.getId();
	}
}